package aip.ui.information.srvc;

import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import aip.core.dao.attachment.AttachmentDao;
import aip.core.dao.information.CatalogDao;
import aip.core.dao.information.InformationDao;
import aip.core.dao.user.UserDao;
import aip.core.model.attachment.Attachment;
import aip.core.model.information.Catalog;
import aip.core.model.information.Information;
import aip.core.model.user.User;
import aip.core.mvc.pageController.PageController;
import aip.ui.information.web.spring.InformationEditForm;
import aip.ui.information.web.spring.InformationListForm;

import com.googlecode.horncomb.bean.filter.SimpleMapConditionSet;
import com.googlecode.horncomb.bean.paged.PagedList;
import com.googlecode.horncomb.bean.paged.PagedSetting;
import com.googlecode.horncomb.web.util.TagUtils;

/**
 * Information form service
 * <p>
 * 负责人/principal:<br/>
 * 修改记录/revision:<br/>
 * 日期:<br/>
 * 修改人:<br/>
 * 修改说明:<br/>
 * @author
 * @version $Id$
 */
public class InformationFormService
{
    private InformationDao informationDao;
    private AttachmentDao attachmentDao;
    private CatalogDao catalogDao;
    private UserDao userDao;

    /**
     * Information列表
     * @param form
     *        表单对象
     * @return 列表页面数据
     * @throws Exception
     */
    public Map<String, Object> listReference(InformationListForm form)
            throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        PagedSetting ps = form.getPagedSettingMap().values().iterator().next();
        if (ps.getConditionSet() == null)
        {
            ps.setConditionSet(new SimpleMapConditionSet());
        }
        PagedList<List<? extends Information>> result = this.informationDao
                .query(ps.getConditionSet(), ps.getOrder(), ps.getPage(),
                        ps.getPageSize());
        if (result.getSource().size() > 0)
        {
            Set<Object> userIds = new HashSet<Object>();
            userIds.addAll(TagUtils.parseIdString(result.getSource(), "creator"));
            userIds.addAll(TagUtils.parseIdString(result.getSource(),
                    "publisher"));
            userIds.addAll(TagUtils.parseIdString(result.getSource(),
                    "lastEditor"));
            List<User> userList = this.userDao.queryListByIds(userIds
                    .toArray(new String[] {}));
            ref.put("userMap", TagUtils.convertToMap(userList, "username"));
        }
        ref.put("informationList", result.getSource()); //$NON-NLS-1$
        ref.put("totalRows", result.getNrOfElements()); //$NON-NLS-1$
        ref.put("cons", ps.getConditionSet().getConstraintsMap());
        ref.put("stateMap", Information.stateMap);
        return ref;
    }

    /**
     * 删除选中的项
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void deleteItems(InformationListForm form) throws Exception
    {
        Assert.notEmpty(form.getSelectedIds());
        this.informationDao.deleteByIds(form.getSelectedIds());
    }

    /**
     * 更改选中新闻状态
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void updateStateByItems(InformationListForm form) throws Exception
    {
        Assert.notEmpty(form.getSelectedIds());
        this.informationDao.updateState(form.getSelectedIds(), form.getState());
    }

    /**
     * 获得Information表单主对象
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void get(InformationEditForm form) throws Exception
    {

        if (form != null && form.getId() > 0)
        {
            Information information = this.informationDao.getById(form.getId());
            BeanUtils.copyProperties(information, form);
        }
    }

    /**
     * 显示编辑Information界面相关数据
     * @param form
     *        表单对象
     * @return 显示页面数据
     * @throws Exception
     */
    public Map<String, Object> showReference(InformationEditForm form)
            throws Exception
    {
        // other reference data
        Map<String, Object> ref = new HashMap<String, Object>();
        if (form.getId() > 0)
        {
            List<? extends Attachment> attachmentList = this.attachmentDao
                    .queryByEntity(form.getId(), Attachment.TYPE_PHOTO);
            ref.put("attachmentList", attachmentList);
        }
        return ref;
    }

    /**
     * 保存Information表单
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void save(InformationEditForm form) throws Exception
    {
        if (form.getId() == 0)
        {
            this.informationDao.insert(form);
        }
        else
        {
            this.informationDao.update(form);
        }
        // for (int i = 0; i < 100; i++)
        // {
        // this.informationDao.insert(form);
        // }
        // 对图片与信息进行关联
        if (StringUtils.hasText(form.getPhotoIds()))
        {
            for (String photoId : form.getPhotoIds().split(","))
            {
                if (StringUtils.hasText(photoId))
                {
                    Attachment attachment = this.attachmentDao.getWithContent(
                            photoId, Attachment.TYPE_PHOTO);
                    attachment.setEntityRefId(form.getId());
                    this.attachmentDao.insertRef(attachment);
                }
            }
        }
        this.delHtmlFile(String.valueOf(form.getId()),
                String.valueOf(form.getCatalog()));
    }

    /**
     * 删除单个Information
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void deleteItem(InformationListForm form) throws Exception
    {
        this.informationDao.deleteById(form.getId());
    }

    /**
     * 更改单个新闻状态
     * @param form
     *        表单对象
     * @throws Exception
     */
    public void updateStateByItem(InformationListForm form) throws Exception
    {
        this.informationDao.updateState(form.getId(), form.getEditState());
    }

    /**
     * 单个栏目信息展现
     * @param form
     * @return
     * @throws Exception
     */
    public Map<String, Object> showIndex(InformationEditForm form)
            throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        // 企业新闻
        List<? extends Information> qyxwInfoList = this.informationDao
                .queryByType(6, 7);
        ref.put("qyxwInfoList", qyxwInfoList);
        // 行业新闻
        List<? extends Information> hyxwInfoList = this.informationDao
                .queryByType(7, form.getPageSize());
        ref.put("hyxwInfoList", hyxwInfoList);
        // 最新资讯
        List<? extends Information> zxzxInfoList = this.informationDao
                .queryByType(27, form.getPageSize());
        ref.put("zxzxInfoList", zxzxInfoList);

        // 推荐产品(至顶的产品) sticky
        List<? extends Information> tjcpInfoList = this.informationDao
                .queryByType(8, 10, true, true);
        ref.put("tjcpInfoList", tjcpInfoList);

        // 产品
        List<? extends Information> cpxxInfoList = this.informationDao
                .queryByType(8, 8, null, true);
        ref.put("cpxxInfoList", cpxxInfoList);

        // 技术服务
        List<? extends Information> jsfwInfoList = this.informationDao
                .queryByType(23, 4);
        ref.put("jsfwInfoList", jsfwInfoList);
        // 资质证书
        List<? extends Information> zzzsInfoList = this.informationDao
                .queryByType(21, 4);
        ref.put("zzzsInfoList", zzzsInfoList);

        // 公司简介
        ref.put("csjj", this.informationDao.getById(1));
        return ref;
    }

    /**
     * 公共栏目展现
     * @param form
     * @return
     * @throws Exception
     */
    public Map<String, Object> showCommIndex(InformationEditForm form)
            throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        List<? extends Information> informations = this.informationDao
                .queryByType(form.getCatalog(), form.getStart() + 1, 8,
                        form.getIsShowSub());
        ref.put("informations", informations);
        Catalog catalog = this.catalogDao.getAllCatalog()
                .get(form.getCatalog());
        String url = "..".concat(catalog.getUrl());
        // 分页
        if (informations.size() > 0)
        {
            PageController pc = new PageController();
            pc.setPageSize(8);
            pc.setRowCount(this.informationDao.getDataCount(form.getCatalog(),
                    form.getIsShowSub()));
            pc.setShowPage(form.getStart());
            pc.setUrl(url);
            pc.setShowPageEnum(new Boolean(true));
            pc.setDivClassName("page");
            pc.setShowInput(new Boolean(true));
            pc.setShowPageEnumCount(5);
            pc.setButtonClassName("pageGoButton");
            pc.setInputClassName("pageInput");
            ref.put("pageStr", pc.getPageController());
        }
        int catalogId = catalog.getSuperior() == null ? catalog.getId()
                : catalog.getSuperior();
        ref.put("leftCataId", catalogId);
        ref.putAll(this.getInfoAndCatalog(form, true));
        return ref;
    }

    /**
     * 新闻展现
     * @param form
     * @return
     * @throws Exception
     */
    public Map<String, Object> showInfo(InformationEditForm form)
            throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        Catalog catalog = this.catalogDao.getAllCatalog()
                .get(form.getCatalog());
        int catalogId = catalog.getSuperior() == null ? catalog.getId()
                : catalog.getSuperior();
        ref.put("leftCataId", catalogId);
        ref.putAll(this.getInfoAndCatalog(form, false));
        return ref;
    }

    /**
     * 公共取栏目信息
     * @param form
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getInfoAndCatalog(InformationEditForm form,
            boolean isMoveSelf) throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        Catalog catalog = this.catalogDao.getAllCatalog()
                .get(form.getCatalog());
        ref.put("catalog", catalog);
        LinkedHashMap<Integer, Catalog> catalogMap = new LinkedHashMap<Integer, Catalog>();
        if (catalog.getSuperior() != null)
        {

            catalogMap.putAll(this.catalogDao.getCatalogMap()
                    .get(catalog.getSuperior()).getChildren());
            if (isMoveSelf)
            {
                catalogMap.remove(catalog.getId());
            }
            ref.put("catalogList", catalogMap.values());
            ref.put("realCatalog",
                    this.catalogDao.getRealCatalog(catalog.getSuperior()));
        }
        Map<Integer, List<Information>> informationMap = new HashMap<Integer, List<Information>>();
        for (Catalog o : catalogMap.values())
        {
            List<Information> informationList = (List<Information>) this.informationDao
                    .queryByType(o.getId(), 10);
            if (informationList.size() > 0)
            {
                informationMap.put(o.getId(), informationList);
            }
        }
        ref.put("allCatalogMap", this.catalogDao.getAllCatalog());
        ref.put("informationMap", informationMap);
        return ref;
    }

    /**
     * 公共搜索
     * @param form
     * @return
     * @throws Exception
     */
    public Map<String, Object> searchCommIndex(InformationEditForm form)
            throws Exception
    {
        Map<String, Object> ref = new HashMap<String, Object>();
        List<? extends Information> informations = this.informationDao
                .queryByType(form.getLikeStr(), form.getStart() + 1, 8,
                        form.getIsShowSub());
        ref.put("informations", informations);
        String url = "../information/informationSearch.shtml?likeStr="
                .concat(form.getLikeStr());
        // 分页
        if (informations.size() > 0)
        {
            PageController pc = new PageController();
            pc.setPageSize(8);
            pc.setRowCount(this.informationDao.getDataCount(form.getLikeStr(),
                    form.getIsShowSub()));
            pc.setShowPage(form.getStart());
            pc.setUrl(url);
            pc.setShowPageEnum(new Boolean(true));
            pc.setDivClassName("page");
            pc.setShowInput(new Boolean(true));
            pc.setShowPageEnumCount(5);
            pc.setButtonClassName("pageGoButton");
            pc.setInputClassName("pageInput");
            ref.put("pageStr", pc.getPageController());
        }
        ref.put("allCatalogMap", this.catalogDao.getAllCatalog());
        return ref;
    }

    /**
     * 删除html文件
     * @param id
     * @param catalogId
     * @throws Exception
     */
    @SuppressWarnings("deprecation")
    public void delHtmlFile(String id, String catalogId) throws Exception
    {
        String menuUrl = CatalogDao.allCatalog.get(Integer.valueOf(catalogId))
                .getUrl();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        String htmlFilePath = request.getRealPath("html");
        try
        {
            if (menuUrl.contains("infoDetail") || menuUrl.contains("infoList"))
            {
                htmlFilePath = htmlFilePath.concat("\\infoDetail_id_")
                        .concat(id).concat(".html");
            }
            else
            {
                htmlFilePath = htmlFilePath.concat("\\proDetail_id_")
                        .concat(id).concat(".html");
            }
            // 如果文件存在刚先删除文件
            File file = new File(htmlFilePath);
            if (file != null)
            {
                file.delete();
            }
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    /**
     * @param informationDao
     *        the informationDao to set
     */
    public void setInformationDao(InformationDao informationDao)
    {
        this.informationDao = informationDao;
    }

    /**
     * @param attachmentDao
     *        the attachmentDao to set
     */
    public void setAttachmentDao(AttachmentDao attachmentDao)
    {
        this.attachmentDao = attachmentDao;
    }

    /**
     * @param catalogDao
     *        the catalogDao to set
     */
    public void setCatalogDao(CatalogDao catalogDao)
    {
        this.catalogDao = catalogDao;
    }

    /**
     * @param userDao
     *        the userDao to set
     */
    public void setUserDao(UserDao userDao)
    {
        this.userDao = userDao;
    }
}
